<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="referrer" content="no-referrer" />
    <title>三维航线demo</title>
    <style>
        body {
            position: absolute;
            margin: 0;
            width: 100%;
            height: 100%;
        }

        #mapContainer {
            left: 0px;
            top: 0px;
            width: 100%;
            height: 100%;
            float: left;
        }
    </style>
</head>

<body>

    <div id="mapContainer" style="position: relative;">
    </div>

</body>
<!-- <script src='http://localhost:9000/examples/GiswayEngine.js'></script> -->
<!-- <script src='/GiswayEngine.js'></script> -->
<script src='/GiswayEngine.js'></script>
<script type="text/javascript">
    var cameraFov = 10; //相机视角
    var mapType = 'satellite'; //electronic
    window.app = new GE.App('mapContainer', {
        geographySystem: 'gcj02',
        //rjy_osgb_output数据  
        position: [118.76769049871781, 31.828401267358743, 3000],
        lookAt: [118.76769049871781, 31.828401267358743, 0],
        // position: [120.170646, 30.28362, 3000],
        // lookAt: [120.170646, 30.28362, 0],

        cameraScrollSpeed: 15,
        minZoom: 3,
        maxZoom: 21,
        cameraFov: cameraFov, //相机的fov
        verticalLevel: 6,
        maxSlopeAngle: 70,

        ambientLightIntensity: 2,
        ambientLightcolor: 0xffffff,//环境光照的颜色
        ambientLightType: 'ambient',//环境光照的类型，有如下类型:ambient，hemisphere
        supportLightType: 'single',//方向光的类型，有如下类型:single，double，tripple
        supportLightIntensity: 1,//方向光的强度
        supportLightcolor: '#ffffff', //方向光的颜色
        lightDistance: 2000,//方向光源距离初始相机target的距离
        lightHeight: 50,//方向光源的高度

        // extraStep: 5,
        patchLoadCount: 7,
        useCarpet: true,
        background: "Fog",
        // backGroundColor: "#A9A9A9",
        useDefaultTexture: false, //是否使用瓦片默认纹理
        isOpenCircleRange: true, //开启圆形范围可视化
        baseLayer: [
            {
                // url: ' https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
                // url: 'https://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}', //高德的瓦片底图
                // url: 'http://webst03.is.autonavi.com/appmaptile?style=7&x={x}&y={y}&z={z}',
                url: 'https://webst03.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
                readableUrl: true,
                tileType: 'image', //图层的类型
                name: 'imageLayer', //图层的名字
                maxDataLevel: 18,
                colorSpace: 'srgb', //'', 
                isBackgroundLayer: true, //该图层是否作为地图的背景图层，一般背景图层都放在所有图层的最下面
            },
            // {
            //     url: 'https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8',
            //     readableUrl: true,
            //     tileType: 'image', //图层的类型
            //     name: 'roadLayer', //图层的名字
            //     maxDataLevel: 18,
            //     colorSpace: 'srgb', //'', 
            //     isAdditionalLayer: true,
            //     isBackgroundLayer: false, //该图层是否作为地图的背景图层，一般背景图层都放在所有图层的最下面
            // },
            //  {
            //     wmsUrl: 'https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8',
            //     wmsUrlDecimal: true,
            //     tileType: 'wms',
            //     canNotSelect: true, //true表示该图层不参与射线拾取，false表示图层参与射线拾取
            // }
        ]
    });

    

    var threeTileModel;
    tiles3d(); //加载倾斜摄影数据
    function tiles3d() {
        threeTileModel = new GE.Tiles3d({
            // url: 'http://localhost:9009/examples/resources/osgb/rjy_osgb_output/tileset.json', refinement: 500, loadRange: 0,//rjy_osgb_output数据
            // url: 'http://192.168.50.155:9009/examples/resources/osgb/rjy_osgb_output/tileset.json', refinement: 500, loadRange: 0,//rjy_osgb_output数据
            url: 'https://gisdata.t-aaron.com/3dTiles/rjy/rjy_osgb_output/tileset.json', refinement: 1000, loadRange: 0,//rjy_osgb_output数据
            // url: 'http://localhost:9009/examples/resources/osgb/银杏湖/tileset.json', refinement: 100, loadRange: 0,//银杏湖数据
            z: -15, //调整数据的高度
            minSize: 500,
            maxSize: 3000,
            // minSize: 10,
            // maxSize: 50,
            maxBytesSize: 0.3 * 2 ** 10,
            minByteSize: 0.2 * 2 ** 10,
            screenErrorFactor: 1.5, //屏幕误差缩放的倍数
            isOpenAdditionalCamera: false, //是否添加预加载的额外相机
            additionCameraFov: cameraFov * 2, //额外相机的fov
            unloadPercent: 1,
            maxJobs: 15,
            canNotSelect: false, //true表示该图层不参与射线拾取，false表示图层参与射线拾取
            isSupportTransparent: false,
            isDoubleSide: false, //是否开启双面渲染
            // dracoGltfPath: 'http://localhost:9009/examples/resources/plugin/draco/gltf/', //draco压缩的gltf文件解压后存放的路径
            // dracoGltfPath: 'http://192.168.50.155:9009/examples/resources/plugin/draco/gltf/', //draco压缩的gltf文件解压后存放的路径
            dracoGltfPath: 'https://gisdata.t-aaron.com/3dTiles/rjy/draco/',
            isCloseGround: true, //是否贴近地面
            isReplaceMaterial: true,
            isComputeBox: true, //计算各个瓦片的包围盒
        });
        app.add(threeTileModel);
        window.tiles3d = threeTileModel;
    }

    var circleCenter = new GE.Point(118.77056629194372, 31.829093937789175, 0, 'gcj02'); //0
    var circleRadius = 700;
    let iconUrl = 'http://localhost:9009/examples/resources/image/airportBox.png'
    var rangeCircle = new GE.CircleRange({ name: 'CS001虚拟机场综管', iconUrl: iconUrl, nameColor:'#FFFAFA', nameLabelColor:'#1E90FF', falldownSurface: threeTileModel, circelCenter: circleCenter, circleRadius: circleRadius, circleBorderWidth: 10, circleRangeColor: '#00FA9A', circleBorderColor: '#0000FF', circleRangeMix: 0.2, falldownSurface: threeTileModel});
    rangeCircle.openRange();


    let point1 = new GE.Point(118.76769049871781, 31.828401267358743, 20, 'gcj02');
    point1['testData'] = 'abndd';
    //let point2 = new GE.Point(118.76769049871781,31.838401267358743,20,'gcj02');
    let point2 = new GE.Point(118.76779049871781, 31.828401267358743, 20, 'gcj02');
    point2['testData'] = 'ghghghh';
    let point3 = new GE.Point(118.76769049871781, 31.828701267358743, 20, 'gcj02');
    point3['testData'] = '2333';
    let point4 = new GE.Point(118.76789049871781, 31.828401267358743, 20, 'gcj02');
    point4['testData'] = '2333';
    let tileMap = app.map.getTileMap('image', 'imageLayer');
    var flightParam = {
        // pointArray: [point1, point2, point3, point4],
        lineColor: '#0472FE', //'#00FF7F', //'#0472FE',
        blockedColor: '#000000',
        lineWidth: 8,  //线的宽度
        editMode: 'sameHeight', //'addHeight', //
        initHeight: 20, //航线的初始高度
        grounds: [tileMap, threeTileModel],
        minDistanceFromGround: 20,
        maxDistanceFromGround: 600,
        // sidewipeDistance: 5, //擦边的距离
        keybordDistance: 0.5,
        stencilRef: 5, //模版测试的值
        narrowCountFactor: 1, //箭头数量的控制参数
        narrorColor: '#FAEBD7'
    };
    var verticalParam = {
        color: '#7FFFD4',
        lineWidth: 2,  //线的宽度
    };
    var flightRange = { circelCenter: circleCenter, circleRadius: circleRadius };
    var editFlight = new GE.EditFlight(flightParam, verticalParam, flightRange);

    //航点高度不安全，给出提示
    window.app.on('dangerWaypoint', function (dangerSign, index) {
        if (dangerSign == 0) {
            console.log('注意：航点高度距离参考地形高度太近，请注意安全。', index);
        } else if (dangerSign == 1) {
            console.log('注意：航点高度达到最大高度。', index);
        }

    });
    
    window.app.on('changeWayPoint', function (operatorType, index) {
        if (operatorType == 'addPoint') { //添加航点

        } else if (operatorType == 'updatePoint') { //修改航点(拖拽航点/调用editFlight.updatePoin接口都会触发这里)

        } else if (operatorType == 'removePoint') { //删除航点(调用调用editFlightremovePoint接口会触发这里)

        } else if (operatorType == 'selectPoint') { //选中一个航点   update!

        } else if (operatorType == 'unSelectPoint') { //取消选中航点

        }
        let flightPointArray = editFlight.getFlightPointArray(); //获取当前航点的数组
        console.log(operatorType, index);
        console.log(flightPointArray[index]);
    });

    //通过API把地图设置为二维地图
    // window.app.map.setVerticalMap();

    //通过API把地图设置为三维地图
    // window.app.map.setMapPitchAngle(45)

    //通过API修改航点
    // editFlight.updatePoint(index, new GE.Point(118.76769049871781, 31.828401267358743, 0, 'gcj02')); //这里的数值前端传入

    //通过API删除航点
    // editFlight.removePoint(0);

    // let isFlightSafe = editFlight.checkFlightSafe();
    // console.log('航线是否安全：'+isFlightSafe);

    window.app.on('throughWall', function () { //拖拽航点时，如果航线穿越障碍物，会触发这里
        console.log('航线会穿越障碍物，请注意安全');
    });

    window.app.on('sideWipe', function () { //拖拽航点时，如果航线穿越障碍物，会触发这里   update!
        console.log('航线可能会有危险，请注意安全');
    });

    window.app.on('crossRange', function () { //拖拽航点时，如果航线穿越障碍物，会触发这里
        console.log('航点超出了最大范围');
    });

    window.app.on('MapRotateEnd', function(){
        let pitchAngle = window.app.map.getPitchAngle();
        if(pitchAngle <= 0.01){
            console.log('当前处于二维状态');
        }
    });

    let isEdit = false; //是否处于编辑航线的状态
    btn();
    function btn() {
        let button0 = new GE.Button('开始编辑航点', function () {
            if(isEdit == false){
                button0.setButtonValue('关闭编辑航点');
                editFlight.startOperator(); //规划航线   update!
                isEdit = true; //航线处于编辑状态
            }else{
                button0.setButtonValue('开始编辑航点');
                editFlight.closeOperator() //规划航线结束
                isEdit = false; //航线不处于编辑状态
            }
           
        });
        app.ui.add(button0);

        // let button1 = new GE.Button('关闭编辑航点', function () {
        //     editFlight.startOperator(2) //规划航线结束 update!
        // });
        // app.ui.add(button1);
        // window.button = button1;

        let button3 = new GE.Button('切换底图', function () {
            if (mapType == 'satellite') { //卫星底图
                mapType = 'electronic';
                app.map.removeTileMap('image', 'imageLayer');
                app.map.addTileMap(
                    {
                        url: 'https://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}', //高德的瓦片底图
                        // url: 'https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8',
                        readableUrl: true,
                        tileType: 'image', //图层的类型
                        name: 'imageLayer', //图层的名字
                        maxDataLevel: 18,
                        colorSpace: 'srgb',
                    }
                );
            } else { //电子底图
                mapType = 'satellite';
                app.map.removeTileMap('image', 'imageLayer');
                app.map.addTileMap(
                    {
                        url: 'https://webst03.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
                        // url: 'https://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=8',
                        // url: 'https://wprd04.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=7',
                        // url: 'https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8',
                        readableUrl: true,
                        tileType: 'image', //图层的类型
                        name: 'imageLayer', //图层的名字
                        maxDataLevel: 18,
                        colorSpace: 'srgb',
                    }
                );
            }
            app.map.load();
        });
        app.ui.add(button3);
    }

    function addRoadMap() {
        let roadMapConfig = {
            url: 'https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8',
            readableUrl: true,
            tileType: 'image', //图层的类型
            name: 'roadLayer', //图层的名字
            maxDataLevel: 18,
            colorSpace: 'srgb', //'', 
            isAdditionalLayer: true
        };
        app.map.addTileMap(roadMapConfig);
        app.map.load();
    }

    window.app.on('Click', function (e) {
        console.log(e.lnglat);
    });



     var pathPolyline; //规划的无人机路线组件
    var flyedPolyline; //无人机真正飞过的路线组件
    var lineWidth = 10; //路线组件的宽度
    function addFlyPath(path) {//添加轨迹线
        let stencilRef = 5;
        let flyedLineData = {
            // pointArray: path,  //多边形的顶点数组
            color: '#F0A032',
            lineWidth: lineWidth,  //线的宽度
            transparent: true,
            opacity: 1,
            depthTest: true,
            stencilRef: stencilRef
        };
        flyedPolyline = new GE.Polyline(flyedLineData);
        flyedPolyline.renderOrder = 1;
        window.app.add(flyedPolyline);

         let pathLineData = {
            pointArray: path,  //多边形的顶点数组
            color: '#0472FE',
            lineWidth: lineWidth,  //线的宽度
            transparent: true,
            opacity: 1,
            depthTest: true,
        };
        pathPolyline = new GE.Polyline(pathLineData);
        pathPolyline.renderOrder = 2;
        pathPolyline.filterStencil(stencilRef);
        window.app.add(pathPolyline);


        let routeArrow = new GE.RouteArrow({pointArray: path, narrorColor: "#ffffff", narrowCountFactor: 1, stencilRef: stencilRef});



         const endPOI = new GE.Poi2({
            position: path[path.length-1],
            name: '',
            baseImageSize: 400,
            showText: false,
            center: [0.5, 0],
            depthTest: true,
            defaultShape: 'square',
            shapeSize: 2.5,
            shapeColor: '#FF6B6B',
            shapeStrokeWidth: 0,
        });
        endPOI.updateTextLayout('image-only');
        // 加载纹理图片 - 直接传入URL字符串
        endPOI.updateShapeTexture('../assets/img/ed.png');
        endPOI.renderOrder = 6;
        endPOI.position.z += 1;
        app.add(endPOI);
    }

    let pointArray = [ //3857表示web墨卡托坐标系，4326表示经纬度坐标
        new GE.Point(120.170646, 30.28362, 20, '4326'),
        new GE.Point(120.175646, 30.28362, 20, '4326'),
        new GE.Point(120.175646, 30.28662, 20, '4326'),
        // new GE.Point(120.175346, 30.28662, 20, '4326'),
        // new GE.Point(120.176346, 30.28362, 20, '4326'),
    ];
    // addFlyPath(pointArray);






    
    var loadedModelCount = 0;
    var isHasdAircraftModel = false; //加载无人机模型是否成功
    var aircraftModel; //无人机模型
    function loadFbx(modelUrl, scale, isComputeBox) {
        var model = new GE.OverLay({
            type: 'fbx',
            url: modelUrl,
            scale: [scale, scale, scale],
            actionTimeScale: 10,
            isComputeBox: isComputeBox, //计算各个瓦片的包围盒
            success: function (modelScene) {
                loadedModelCount++;
                if (loadedModelCount >= 2) {
                    isHasdAircraftModel = true;

                    debugger
                    const boundingBox = new GE.three.Box3();
                    // 递归计算对象A及其所有子对象的包围盒
                    boundingBox.setFromObject(aircraftModel);

                    // 获取包围盒尺寸
                    const size = new GE.three.Vector3();
                    boundingBox.getSize(size);

                    let maxSize = Math.max(size.x, size.y, size.z);
                    let targetSize = 2;
                    let scaleFactor = targetSize / maxSize;
                    aircraftModel.scale.set(scaleFactor, scaleFactor, scaleFactor);
                }
            }
        });
        return model;
    }

    function loadAircraftModel() {
        aircraftModel = loadFbx('/examples/resources/fbx/wurenji3.fbx', 1, false);
        aircraftModel.up.x = 0; aircraftModel.up.y = 0; aircraftModel.up.z = 1;  //提供模型的朝向信息，不然模型移动的时候可能会出现朝向错误
        aircraftModel.renderOrder = 4;
        let aircraftModelPosition = new GE.Point(118.77027405720378, 31.827397316113515, 40, 'gcj02').toEPSGWeb();
        aircraftModel.position.copy(aircraftModelPosition);
        app.add(aircraftModel);

        var directionModel = loadFbx('/examples/resources/fbx/direction1.fbx', 0.2, false);
        directionModel.position.y += 10;
        directionModel.position.z += 55;
        directionModel.rotateX(-Math.PI / 2);
        aircraftModel.add(directionModel);

        let SphereGeometry = new GE.three.SphereGeometry(120)
        let sphereMaterial = new GE.three.MeshBasicMaterial({ color: '#0000FF', transparent: true, opacity: 0.2 })
        let sphere = new GE.three.Mesh(SphereGeometry, sphereMaterial)
        sphere.renderOrder = 5;
        aircraftModel.add(sphere);
    }
    loadAircraftModel(); //加载无人机模型

</script>

</html>